package cn.laixueit.upload;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
@CrossOrigin
public class UploadController {

    @PostMapping("/image")
    public ResponseEntity<String> uploadImg(@RequestParam MultipartFile file) throws IOException {

        String pathName = "";
        try {
            InputStream inputStream = file.getInputStream();
            String oldName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            pathName = uuid+oldName;
            upload(inputStream, pathName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseEntity.ok("https://chuangmei2.oss-cn-hangzhou.aliyuncs.com/" + pathName);
    }

    private void upload(InputStream file, String filename) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI4GBm8U2SQe9kncWiWof8";
        String accessKeySecret = "D0wHwgZFmhgr2ULFVP9Oa8R40vcSn3";

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
// 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
        ossClient.putObject("chuangmei2", filename, file);

// 关闭OSSClient。
        ossClient.shutdown();
    }
}
